package com.amzing.dynamicrulesshardingjdbc.config.datasource;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.InlineShardingStrategyConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.*;

@Configuration
public class DynamicRuleDatasourceConfig {

    @Bean
    public DataSource init() throws SQLException {
        // 配置真实数据源
        Map<String, DataSource> dataSourceMap = new HashMap<>();

        // 配置第一个数据源
        HikariDataSource dataSource1 = new HikariDataSource();
        dataSource1.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource1.setJdbcUrl("jdbc:mysql://localhost:3306/ds0");
        dataSource1.setUsername("root");
        dataSource1.setPassword("sinA01234.");
        dataSourceMap.put("ds0", dataSource1);

        Properties properties = new Properties();
        properties.setProperty("sql.show", "true");

        // 获取数据源对象
        DataSource dataSource = DynamicRulesShardingDataSourceFactory.createDataSource(dataSourceMap, initRuleConfig(), properties);
        return dataSource;
    }

    public ShardingRuleConfiguration initRuleConfig(){

        // 配置Order表规则
        TableRuleConfiguration orderTableRuleConfig = new TableRuleConfiguration("t_order","ds0.t_order_${[1,2]}");
        // 配置分库 + 分表策略
        //orderTableRuleConfig.setDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration("user_id", "ds${user_id % 2}"));
        orderTableRuleConfig.setTableShardingStrategyConfig(new InlineShardingStrategyConfiguration("tenant_id", "t_order_${tenant_id}"));

        // 配置Order表规则
        TableRuleConfiguration orderItemTableRuleConfig = new TableRuleConfiguration("t_order_item","ds0.t_order_item_${[1,2]}");
        //分表策略
        orderItemTableRuleConfig.setTableShardingStrategyConfig(new InlineShardingStrategyConfiguration("tenant_id", "t_order_item_${tenant_id}"));

        List<String> bindingTableGroups = new ArrayList<>();
        bindingTableGroups.add("t_order");
        bindingTableGroups.add("t_order_item");

        // 配置分片规则
        ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
        shardingRuleConfig.getTableRuleConfigs().add(orderTableRuleConfig);
        shardingRuleConfig.getTableRuleConfigs().add(orderItemTableRuleConfig);
        shardingRuleConfig.setBindingTableGroups(bindingTableGroups);

        return shardingRuleConfig;
    }
}
